package emailserving.common;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.joda.time.DateTime;
import org.joda.time.Minutes;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by jack on 2/16/16.
 */
public class Utils {
    public static final Pattern emailPattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

    public static <T> List<T> pagination(List<T> list, int pageIndex, int pageSize) {
        Validate.notNull(list);
        final int totalSize = list.size();
        pageIndex = pageIndex < 0 ? 0 : pageIndex;
        int startIndex = Math.max(pageIndex * pageSize, 0);
        startIndex = Math.min(startIndex, totalSize);
        int endIndex = startIndex + pageSize;
        endIndex = Math.min(endIndex, totalSize);
        return list.subList(startIndex, endIndex);
    }

    public static <T> List<List<T>> getPaginationList(List<T> list, int pageCount) {
        Validate.notNull(list);
        if (!list.isEmpty()) {
            List<List<T>> pageResult = Lists.newArrayList();
            int pageSize = Math.max((list.size() + 1) / pageCount, 1);
            for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) {
                pageResult.add(pagination(list, pageIndex, pageSize));
            }
            return pageResult;
        } else {
            return Lists.newArrayList();
        }
    }

    public static long diffMinutesBetween2Date(Date date, Date anotherDate) {
        Preconditions.checkArgument(date != null);
        Preconditions.checkArgument(anotherDate != null);
        return Math.abs(Minutes.minutesBetween(new DateTime(date), new DateTime(anotherDate)).getMinutes());
    }

    public static boolean validateItsEmailFormat(String email) {
        return StringUtils.isNotEmpty(email) && emailPattern.matcher(StringUtils.trim(email)).matches();
    }
}
